﻿using System;
using System.Collections.Generic;
using System.Text;
using Windows.Security.Credentials;
using System.Linq;

namespace JiveMessenger.Utilities
{
    public static class CredentialsManager
    {
        //using Windows.Security.Credentials;
        private const string RESOURCE_NAME = "JiveMessenger.net";

        public static void SaveCredential(string userName, string password)
        {
            if (string.IsNullOrEmpty(userName) || string.IsNullOrEmpty(password))
                return;
            var vault = new PasswordVault();
            var credential = new PasswordCredential(RESOURCE_NAME, userName, password);

            // Permanently stores credential in the password vault.
            vault.Add(credential);
        }

        public static string GetStoredPasswordForUser(string username)
        {
            var vault = new PasswordVault();
            string password = "";
            try
            {
                var list = vault.FindAllByUserName(username);

                if (list.Count > 0)
                {
                    PasswordCredential cred = list.FirstOrDefault();
                    cred.RetrievePassword();
                    password = cred.Password;
                }
            }
            catch (Exception)
            {
                // If no credentials have been stored with the given RESOURCE_NAME, an exception
                // is thrown.
            }
            return password;
        }

        public static void RemoveCredential(string userName)
        {
            if(string.IsNullOrEmpty(userName))
                return;
            var vault = new PasswordVault();
            try
            {
                // Removes the credential from the password vault.
                vault.Remove(vault.Retrieve(RESOURCE_NAME, userName));
            }
            catch (Exception)
            {
                // If no credentials have been stored with the given RESOURCE_NAME, an exception
                // is thrown.
            }
        }
    }
}
